package com.org.manhu.chargehelper.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.os.Environment;

/**
 * @文件名：FileUtil.java
 * @包名：com.org.manhu.chargehelper.tools
 * @作者：李朋辉 @QQ：892839211
 * @创建时间：2015年2月10日 下午10:05:46
 *
 * @描述：
 */
public class FileUtil {

	/**
	 * @描述：读取文件中的内容
	 * @param fileName
	 * @return
	 */
	public static String readFileData(String path) {
		String str = "";
		try {
			File f = new File(path);
			FileInputStream fin = new FileInputStream(f);
			int length = fin.available();
			byte[] bytes = new byte[length];
			fin.read(bytes);
			str = new String(bytes);
			fin.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}

	public static String getFileName(String input) {
		return new File(input).getName();
	}

	public static String save2File(String name, String e) {
		String fileName = name + ".txt";

		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			String path = "/mnt/sdcard/manhu/crash/";
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			FileOutputStream fos;
			try {
				fos = new FileOutputStream(path + fileName);
				fos.write(e.toString().getBytes());
				fos.close();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		return fileName;
	}

	/**
	 * 
	 * @描述：判断文件是否存在
	 * @param path
	 * @return
	 */
	public static boolean isFileExit(String path) {
		File file = new File(path);
		if (file.exists()) {
			return true;
		}
		return false;
	}

	/**
	 * @描述：判断文件是否存在
	 * @param id
	 * @param path
	 * @return
	 */
	public static boolean isVideoExits(String id, String path) {
		String localPath = "/mnt/sdcard/manhu/video/" + id + "/";
		String fileName = StringUtils.getFileName(path);
		File videoFile = new File(localPath + fileName);
		if (videoFile.exists()) {
			return true;
		}
		return false;
	}

	/**
	 * @描述：递归删除文件
	 * @param file
	 */
	public static void delete(File file) {
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
				return;
			}

			if (file.isDirectory()) {
				File[] childFiles = file.listFiles();
				if (childFiles == null || childFiles.length == 0) {
					file.delete();
					return;
				}

				for (int i = 0; i < childFiles.length; i++) {
					delete(childFiles[i]);
				}
				file.delete();
			}

		}
	}

}
